package com.ddwl.goods.service;

import com.ddwl.goods.dao.DiscountDao;
import com.ddwl.goods.dao.model.Discount;
import com.ddwl.goods.mapper.ActivityMapper;
import com.ddwl.goods.model.Activity;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.goods.ActivityBo;
import com.ddwl.schema.bo.goods.DiscountBo;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.goods.ActivityListVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ActivityService {

    private final DiscountDao discountDao;
    private final ActivityMapper activityMapper;

    public PageVo<ActivityListVo> activityList(PageBo<ActivityBo> pageBo) {
        PageVo<ActivityListVo> pageVo = new PageVo<>();
        BeanUtils.copyProperties(pageBo, pageVo);
        pageVo.setSize(pageBo.getPageSize());
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize());
        Page<Activity> pageable = (Page<Activity>) activityMapper.findAll(pageBo.getParam());
        pageVo.setTotal(pageable.getTotal());
        pageVo.setData(pageable.getResult().stream().map(activity -> {
            ActivityListVo activityVo = new ActivityListVo();
            BeanUtils.copyProperties(activity, activityVo);
            return activityVo;
        }).collect(Collectors.toList()));
        return pageVo;
    }

    public String shelf(String activityId, Integer activityStatus) {
        activityMapper.updateStatus(activityId, activityStatus);
        return activityId;
    }

    /**
     * 创建或更新满减购活动信息
     */
    void createOrUpdateDiscount(String activityId, DiscountBo discountBo) {
        discountDao.deleteByActivityId(activityId);
        //新增
        if (discountBo.getId() == null) {
            for (Map.Entry<String, String> entry : discountBo.getDiscountMap().entrySet()) {
                Discount discount = new Discount();
                BeanUtils.copyProperties(discountBo, discount);

                discount.setDiscountNum(entry.getKey());
                discount.setDiscountValue(entry.getValue());
                discountDao.insert(discount);
            }
        } else {
            for (Map.Entry<String, String> entry : discountBo.getDiscountMap().entrySet()) {
                Discount discount = new Discount();
                BeanUtils.copyProperties(discountBo, discount);
                discount.setDiscountNum(entry.getKey());
                discount.setDiscountValue(entry.getValue());
                discountDao.updateByPrimaryKeySelective(discount);
            }
        }

    }
}
